package com.ruitaowang.wap;

import com.ruitaowang.account.security.LYSecurityUtil;
import com.ruitaowang.account.service.SysUserService;
import com.ruitaowang.core.domain.*;
import com.ruitaowang.core.web.BaseController;
import com.ruitaowang.core.web.MsgOut;
import com.ruitaowang.goods.service.*;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class APIWapUserController extends BaseController {
	
	protected final Logger LOGGER = LoggerFactory.getLogger(getClass());

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private CompanyService companyService;
    @Autowired
    private ActivityService activityService;
    @Autowired
    private RelationsService relationsService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private SysUserCompanyService sysUserCompanyService;
    @Autowired
    private GoodsRecommendService goodsRecommendService;
    @Autowired
    private VerifyCodeService verifyCodeService;
    @Autowired
    private UserProfitService userProfitService;

    /**
     * 微传媒个人主页(文章主页)
     * @param activityId
     * @return
     */
    @RequestMapping(value = "/api/wap/userForActivity")
    public String userForActivity(Long activityId,Long userId){
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        Map map = new HashMap();
        Long authorId = (long)0;
        if (activityId != 0) {
            authorId = activityService.selectByPK(activityId).getActivityAuthor();
        } else if (userId != 0) {
            authorId = userId;
        }
        //Long authorId = activityService.selectByPK(activityId).getActivityAuthor();
        SysUser sysUser = sysUserService.selectByPK(authorId);
        Activity activity = new Activity();
        activity.setActivityAuthor(authorId);
        activity.setActivityType((byte) 10);
        //文章数
        Long activeCount = activityService.count(activity);
        String activeCountMoreW;
        if(activeCount > 10000){
            double rw = Double.parseDouble(String.format("%.1f", (double)activeCount / 10000));
            activeCountMoreW = rw + "W";
            //文章数
            map.put("activeCount",activeCountMoreW);
        } else {
            //文章数
            map.put("activeCount",activeCount);
        }
        Relations relations = new Relations();
        relations.setPid(authorId);
        //粉丝数
        long activityFans = relationsService.count(relations);
        String activityFansMoreW;
        if(activityFans > 10000){
            double rw = Double.parseDouble(String.format("%.1f", (double)activityFans / 10000));
            activityFansMoreW = rw + "W";
            //粉丝数
            map.put("activityFans",activityFansMoreW);
        } else {
            //粉丝数
            map.put("activityFans",activityFans);
        }
        //阅读量
        long activityRead = 0;
        String readMoreW;
        List<Activity> activityList = activityService.select(activity);
        for(Activity a : activityList){
            activityRead = activityRead + a.getActivityRead();
        }
        if(activityRead > 10000){
            double rw = Double.parseDouble(String.format("%.1f", (double)activityRead / 10000));
            readMoreW = rw + "W";
            //阅读量
            map.put("activityRead",readMoreW);
        } else {
            //阅读量
            map.put("activityRead",activityRead);
        }
        Company company = companyService.selectByUserId(authorId);
        SysUserCompany sysUserCompany = sysUserCompanyService.selectByUserId(authorId);
        if(user.getId().equals(authorId)){
            //是本人
            map.put("isme","2");
            map.put("lookId",authorId);
        } else {
            //不是本人
            map.put("isme","1");
            map.put("lookId",user.getId());
        }
        //作者Id
        map.put("authorId",authorId);
        //作者信息
        map.put("user",sysUser);
        if (ObjectUtils.isEmpty(company)) {
            //没有首象店铺
            map.put("haveCompany","false");
            map.put("companyId","");
            map.put("isShenhe","0");
        } else {
            //有象相店铺
            map.put("haveCompany","true");
            map.put("companyId",company.getCompanyId());
            if(company.getCompanyStatus() == 0){
                map.put("isShenhe","0");
            } else {
                map.put("isShenhe","1");
            }
        }
        if (ObjectUtils.isEmpty(sysUserCompany)) {
            //没有公司信息
            map.put("havaUserCompany","false");
            map.put("companyName","");
        } else {
            //有公司信息
            map.put("havaUserCompany","true");
            map.put("companyName",sysUserCompany.getCompanyName());
        }
        MsgOut o = MsgOut.success(map);
        return this.renderJson(o);
    }

    /**
     * 微传媒个人主页(我的)
     * @param
     * @return
     */
    @RequestMapping(value = "/api/wap/userForMe")
    public String userForMe(){
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        Map map = new HashMap();
        SysUser sysUser = sysUserService.selectByPK(user.getId());
        Activity activity = new Activity();
        activity.setActivityAuthor(user.getId());
        activity.setActivityType((byte) 10);
        //文章数
        Long activeCount = activityService.count(activity);
        String activeCountMoreW;
        if(activeCount > 10000){
            double rw = Double.parseDouble(String.format("%.1f", (double)activeCount / 10000));
            activeCountMoreW = rw + "W";
            //文章数
            map.put("activeCount",activeCountMoreW);
        } else {
            //文章数
            map.put("activeCount",activeCount);
        }
        Relations relations = new Relations();
        relations.setPid(user.getId());
        //粉丝数
        long activityFans = relationsService.count(relations);
        String activityFansMoreW;
        if(activityFans > 10000){
            double rw = Double.parseDouble(String.format("%.1f", (double)activityFans / 10000));
            activityFansMoreW = rw + "W";
            //粉丝数
            map.put("activityFans",activityFansMoreW);
        } else {
            //粉丝数
            map.put("activityFans",activityFans);
        }
        //阅读量
        long activityRead = 0;
        String readMoreW;
        List<Activity> activityList = activityService.select(activity);
        for(Activity a : activityList){
            activityRead = activityRead + a.getActivityRead();
        }
        if(activityRead > 10000){
            double rw = Double.parseDouble(String.format("%.1f", (double)activityRead / 10000));
            readMoreW = rw + "W";
            //阅读量
            map.put("activityRead",readMoreW);
        } else {
            //阅读量
            map.put("activityRead",activityRead);
        }
        Company company = companyService.selectByUserId(user.getId());
        SysUserCompany sysUserCompany = sysUserCompanyService.selectByUserId(user.getId());
        //是自己
        map.put("isme","2");
        //作者id
        map.put("authorId",user.getId());
        //作者信息
        map.put("user",sysUser);
        if (ObjectUtils.isEmpty(company)) {
            //没有首象店铺
            map.put("haveCompany","false");
            map.put("companyId","");
            map.put("isShenhe","0");
        } else {
            //有首象店铺
            map.put("haveCompany","true");
            map.put("companyId",company.getCompanyId());
            if(company.getCompanyStatus() == 0){
                map.put("isShenhe","0");
            } else {
                map.put("isShenhe","1");
            }
        }
        if (ObjectUtils.isEmpty(sysUserCompany)) {
            //没有公司信息
            map.put("havaUserCompany","false");
            map.put("companyName","");
        } else {
            //有公司信息
            map.put("havaUserCompany","true");
            map.put("companyName",sysUserCompany.getCompanyName());
        }
        MsgOut o = MsgOut.success(map);
        return this.renderJson(o);
    }

    /**
     * 粉丝列表
     * @param relations
     * @return
     */
    @RequestMapping(value = "/api/user/subordinate")
    public String subordinate(Relations relations,int page) {
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        List<SysUser> sysUsers=new ArrayList<>();
        relations.setPage(page);
        List<Relations> relationsList=relationsService.selectForPage(relations);
        for (Relations r : relationsList){
            sysUsers.add(sysUserService.selectByPK(r.getUesrId()));
        }
        MsgOut o = MsgOut.success(sysUsers);
        o.setRecords(relations.getRecords());
        o.setTotal(relations.getTotal());
        return this.renderJson(o);
    }

    /**
     * 积分详情
     *
     * @param userProfit
     * @param page
     * @return
     */
    @RequestMapping(value = "/api/wap/userProfit/all")
    public String findUserProfitAll(@RequestHeader(value="headId",required = false) Long userId,UserProfit userProfit, int page) {
        if (ObjectUtils.isEmpty(userId)){
            return this.renderJson(MsgOut.error("Plz login."));
        }
        userProfit.setUserId(userId);
        userProfit.setPage(page);
        List<UserProfitVO> userProfitVOS= new ArrayList<>();
        List<UserProfit> userProfits=userProfitService.timeForPage(userProfit);
        for (UserProfit up:userProfits){
            UserProfitVO userProfitVO = new UserProfitVO();
            BeanUtils.copyProperties(up,userProfitVO);
            SysUser sysUser=sysUserService.selectByPK(up.getConsumerId());
            if (ObjectUtils.isEmpty(sysUser)){
                userProfitVO.setNickname("");
            }else {
                userProfitVO.setNickname(sysUser.getNickname());
            }
            userProfitVOS.add(userProfitVO);
        }
        MsgOut o = MsgOut.success(userProfitVOS);
        o.setRecords(userProfit.getRecords());
        o.setTotal(userProfit.getTotal());
        return this.renderJson(o);
    }

    /**
     * 个人资料
     * @param userId
     * @return
     */
    @RequestMapping(value = "/api/wap/userInformation")
    public String userInformation(Long userId){
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        Map map = new HashMap();
        //个人信息
        SysUser sysUser = sysUserService.selectByPK(userId);
        SysUserVO sysUserVO = new SysUserVO();
        BeanUtils.copyProperties(sysUser,sysUserVO);
        //首象店铺信息
        Company company = companyService.selectByUserId(userId);
        if (!ObjectUtils.isEmpty(company)) {
            sysUserVO.setRuitaoCompanyName(company.getCompanyName());
        } else {
            sysUserVO.setRuitaoCompanyName("");
        }
        //公司信息
        SysUserCompany sysUserCompany = sysUserCompanyService.selectByUserId(userId);
        //推荐商品
        GoodsRecommend goodsRecommend = new GoodsRecommend();
        List<GoodsRecommend> goodsRecommendList = new ArrayList<>();
        if (!ObjectUtils.isEmpty(company)) {
            goodsRecommend.setCompanyId(company.getCompanyId());
            goodsRecommendList = goodsRecommendService.select(goodsRecommend);
        }
        List<Goods> goodsList = new ArrayList<>();
        for (GoodsRecommend g : goodsRecommendList){
            Goods goods = goodsService.selectByPK(g.getGoodsId());
            GoodsVO goodsVO = new GoodsVO();
            BeanUtils.copyProperties(goods,goodsVO);
            goodsVO.setGoodsRecommendId(g.getId());
            goodsList.add(goodsVO);
        }
        map.put("user",sysUserVO);
        if (ObjectUtils.isEmpty(sysUserCompany)) {
            SysUserCompany sysUserCompany1 = new SysUserCompany();
            sysUserCompany1.setUserId(userId);
            sysUserCompanyService.insert(sysUserCompany1);
            SysUserCompany sysUserCompany2 = sysUserCompanyService.selectByUserId(userId);
            map.put("company",sysUserCompany2);
        } else {
            map.put("company",sysUserCompany);
        }
        map.put("goods",goodsList);
        if (ObjectUtils.isEmpty(company)) {
            //没有公司信息
            map.put("havaCompany","false");
            map.put("companyId","");
        } else {
            //有公司信息
            map.put("havaCompany","true");
            map.put("companyId",company.getCompanyId());
        }
        MsgOut o = MsgOut.success(map);
        return this.renderJson(o);
    }

    /**
     * 公司信息
     * @param userId
     * @return
     */
    @RequestMapping(value = "/api/wap/companyInformation")
    public String companyInformation(Long userId){
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        //公司信息
        SysUserCompany sysUserCompany = sysUserCompanyService.selectByUserId(userId);
        MsgOut o = MsgOut.success(sysUserCompany);
        return this.renderJson(o);
    }

    /**
     * 更新公司信息
     * @param sysUserCompany
     * @return
     */
    @RequestMapping(value = "/api/companyInformation/update", method = RequestMethod.PUT)
    public String companyInformation(SysUserCompany sysUserCompany) {
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        sysUserCompanyService.update(sysUserCompany);
        MsgOut o = MsgOut.success(sysUserCompany);
        return this.renderJson(o);
    }

    /**
     * 更新个人信息
     * @param sysUser
     * @return
     */
    @RequestMapping(value = "/api/userInformation/update", method = RequestMethod.PUT)
    public String userInformationUser(SysUser sysUser,SysUserCompany sysUserCompany) {
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        Map map = new HashMap();
        sysUserService.update(sysUser);
        if (ObjectUtils.isEmpty(sysUserCompanyService.selectByPK(sysUserCompany.getCompanyId()))) {
            sysUserCompany.setUserId(sysUser.getId());
            List<SysUserCompany> sysUserCompanyList = sysUserCompanyService.select(sysUserCompany);
            sysUserCompany.setCompanyId(sysUserCompanyList.get(0).getCompanyId());
        }
        sysUserCompanyService.update(sysUserCompany);
        map.put("user",sysUser);
        map.put("company",sysUserCompany);
        MsgOut o = MsgOut.success(map);
        return this.renderJson(o);
    }

    /**
     * 查询所有商品
     * @param userId
     * @return
     */
    @RequestMapping(value = "/api/user/goods")
    public String allGoods(GoodsVO goodsVO,Long userId,int page) {
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        Company company = companyService.selectByCompanyStaff(userId);
        List<GoodsVO> goodsRecommendList = new ArrayList<>();
        if (!ObjectUtils.isEmpty(company)) {
            goodsVO.setPage(page);
            goodsVO.setCompanyId(company.getCompanyId());
            goodsVO.setGoodsOnline((byte)1);
            goodsRecommendList = goodsRecommendService.selectForSort(goodsVO);
        }
        if (!ObjectUtils.isEmpty(goodsRecommendList)) {
            MsgOut o = MsgOut.success(goodsRecommendList);
            o.setRecords(goodsVO.getRecords());
            o.setTotal(goodsVO.getTotal());
            return this.renderJson(o);
        } else {
            return this.renderJson(MsgOut.error("select goods is null"));
        }
    }

//    @RequestMapping(value = "/api/user/goodsUpate", method = RequestMethod.PUT)
//    public String goodsUpate(GoodsRecommend goodsRecommend,int checkout,Long userId){
//        SysUser user = LYSecurityUtil.currentSysUser();
//        if (ObjectUtils.isEmpty(user)) {
//            return this.renderJson(MsgOut.error("Plz login."));
//        }
//        Company company = companyService.selectByUserId(userId);
//        goodsRecommend.setCompanyId(company.getCompanyId());
//        if (checkout == 1){
//            goodsRecommendService.insert(goodsRecommend);
//        } else if(checkout == 2){
//            goodsRecommendService.delete(goodsRecommend.getId());
//        }
//        MsgOut o = MsgOut.success(goodsRecommendService.select(goodsRecommend));
//        return this.renderJson(o);
//    }

    @RequestMapping(value = "/api/user/goodsUpate", method = RequestMethod.PUT)
    public String goodsUpate(String newGoods,Long goodsProviderId){
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        if (!ObjectUtils.isEmpty(newGoods)) {
            String[] newGoodsList = newGoods.split(",");
            MsgOut o = MsgOut.success(goodsRecommendService.updateRecommendGoods(newGoodsList,goodsProviderId));
            return this.renderJson(o);
        } else {
            MsgOut o = MsgOut.success(goodsRecommendService.deleteByCompany(goodsProviderId));
            return this.renderJson(o);
        }
    }

    /**
     * 根据id删除推荐商品
     * @param id
     * @return
     */
    @RequestMapping(value = "/api/goodsDelete/{id}", method = RequestMethod.DELETE)
    public String deleteActivity(@PathVariable("id") Long id) {
        MsgOut o = MsgOut.success(goodsRecommendService.delete(id));
        return this.renderJson(o);
    }

    /**
     * 新增员工时验证用户
     * @param sysUser
     * @param userId
     * @return
     */
    @RequestMapping(value = "/api/wap/user", method = RequestMethod.GET)
    public String user(SysUser sysUser,@RequestHeader(value="headId",required = false) Long userId) {
        if (ObjectUtils.isEmpty(userId)){
            return this.renderJson(MsgOut.error("Plz login."));
        }
        SysUser sysUser1 = sysUserService.selectByPK(sysUser.getId());
        if (ObjectUtils.isEmpty(sysUser1)){
            return this.renderJson(MsgOut.error("查询不到此用户。"));
        }
        if(!sysUser1.getPhone().equals(sysUser.getPhone())){
        	LOGGER.info("sysUser1.getPhone()：" + sysUser1.getPhone());
        	LOGGER.info("sysUser.getPhone()：" + sysUser1.getPhone());
            return this.renderJson(MsgOut.error("账号与手机号不匹配。"));
        }
        MsgOut o = MsgOut.success("用户可以注册为员工");
        return this.renderJson(o);
    }


    /**
     * 新版商家我的
     * @param userId
     * @return
     */
    @RequestMapping(value = "/api/wap/myCompany")
    public String getCompanyInfo(@RequestHeader(value = "headId", required = false) String userId) {
        if (ObjectUtils.isEmpty(userId)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        SysUser user = sysUserService.selectByPK(Long.parseLong(userId));
        Company company = companyService.selectByCompanyStaff(user.getId());
        if (!ObjectUtils.isEmpty(company)) {
            if (!ObjectUtils.isEmpty(company.getHeadimgurl())) {
                company.setHeadimgurl("http://static.ruitaowang.com/attached/file/2018/07/09/20180709155656054.jpg");
            }
            MsgOut o = MsgOut.success(company);
            return this.renderJson(o);
        } else {
            return this.renderJson(MsgOut.error("您还不是商家用户"));
        }
    }

    /**
     * 账户与安全
     * @param userId
     * @return
     */
    @RequestMapping(value = "/api/wap/myCount")
    public String myCount(@RequestHeader(value = "headId", required = false) String userId) {
        Map map = new HashMap();
        if (ObjectUtils.isEmpty(userId)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        SysUser sysUser = sysUserService.selectByPK(Long.parseLong(userId));
        Company company = companyService.selectByUserId(Long.parseLong(userId));
        String companyType = "首象店铺商家";
        if (ObjectUtils.isEmpty(company)) {
            company = companyService.selectByCompanyStaff(Long.parseLong(userId));
            if (!ObjectUtils.isEmpty(company)) {
                companyType = "首象店铺员工";
            }
        }
        map.put("user",sysUser);
        map.put("companyType",companyType);
        map.put("companyName",company.getCompanyName());
        MsgOut o = MsgOut.success(map);
        return this.renderJson(o);
    }

    /**
     * 更换手机号
     * @param phone
     * @param newPhone
     * @param userId
     * @return
     */
    @RequestMapping(value = "/api/wap/updatePhone", method = RequestMethod.PUT)
    public String updatePhone(String phone,String newPhone,String verifycode1,String verifycode2,@RequestHeader(value = "headId", required = false) String userId){
        if (ObjectUtils.isEmpty(userId)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(newPhone) || StringUtils.isEmpty(verifycode1)
                || StringUtils.isEmpty(verifycode2)) {
            return this.renderJson(MsgOut.error("参数不能为空"));
        }
        SysUser sysUser = sysUserService.selectByPK(Long.parseLong(userId));
        if(!sysUser.getPhone().equals(phone)){
            return this.renderJson(MsgOut.error("请输入正确的手机号."));
        }
        SysUser sysUser1 = new SysUser();
        sysUser1.setPhone(newPhone);
        List<SysUser> sysUserList = sysUserService.select(sysUser1);
        if (!ObjectUtils.isEmpty(sysUserList)) {
            return this.renderJson(MsgOut.error("该手机号已被注册."));
        }
        Verifycode v = new Verifycode();
        v.setMobile(phone);
        List<Verifycode> verifycodes = verifyCodeService.select(v);
        v = verifycodes.get(0);
        if (!verifycode1.equals(v.getVerifycode())) {
            return this.renderJson(MsgOut.error("原手机号验证码错误！"));
        }
        v.setMobile(newPhone);
        List<Verifycode> newVerifycodes = verifyCodeService.select(v);
        v = newVerifycodes.get(0);
        if (!verifycode2.equals(v.getVerifycode())) {
            return this.renderJson(MsgOut.error("新手机号验证码错误！"));
        }
        sysUser.setPhone(newPhone);
        sysUserService.update(sysUser);
        MsgOut o = MsgOut.success(sysUser);
        return this.renderJson(o);
    }

    /**
     * 根据id查询个人信息
     * @return
     */
    @RequestMapping(value = "/api/wap/myUser", method = RequestMethod.GET)
    public String myUser(){
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        SysUser sysUser = sysUserService.selectByPK(user.getId());
        MsgOut o = MsgOut.success(sysUser);
        return this.renderJson(o);
    }

    @RequestMapping(value = "/api/wap/searchUser", method = RequestMethod.GET)
    public String searchUser(SysUserVO sysUserVO){
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        List<SysUser> sysUserList = sysUserService.selectUserForCommunity(sysUserVO);
        MsgOut o = MsgOut.success(sysUserList);
        return this.renderJson(o);
    }
}
